const MAX_LiMIT = 8
let condition = {}
let today = new Date()
today.setHours(0)
today.setMinutes(0)
today.setSeconds(0)

function getDate(delta) {
  return today.getTime() + delta * 24 * 60 * 60 * 1000
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchValue: "",
    filter: false,
    tips: [],
    histories: [],
    result: [],
    noData: false,
    type: [{
      name: '失物(lost)',
      value: 'lost'
    }, {
      name: '招领(found)',
      value: 'found'
    }],
    status: [{
      name: '寻找中/待领中',
      value: 'progress'
    }, {
      name: '已找回/已认领',
      value: 'finish'
    }]
  },

  /**
   * 跳转搜索
   */
  wxSearchTab: function () {
    wx.navigateTo({
      url: '../search/search'
    })
  },

  //加载标签
  _loadTags: function () {
    let _this = this
    wx.cloud.callFunction({
      name: "tags",
      data: {
        $url: 'getTags'
      }
    }).then(res => {
      if (res.result.code === 200) {
        _this.setData({
          tags: res.result.data[0].lists
        })
      }
    })
  },

  // 获取数据
  async _loadData() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let res = null
    let keyword = this.data.searchValue
    try {
      res = await wx.cloud.callFunction({
        name: "search",
        data: {
          $url: 'search',
          skip: this.data.result.length,
          limit: MAX_LiMIT,
          keyword,
          condition
        }
      })
    } catch (err) {
      console.log(err)
    }
    console.log(res)
    for (let o in res.result.data) {
      res.result.data[o].date = (new Date(res.result.data[o].date)).getTime()
    }
    this.setData({
      result: [...this.data.result, ...res.result.data],
      noData: res.result.data.length < MAX_LiMIT
    })
    wx.stopPullDownRefresh()
    wx.hideLoading()
  },

  /**
   * 检查是否登录
   */
  async _loadPersonalInfo() {
    const db = wx.cloud.database();
    let user;
    try {
      user = await db.collection('users').get()
    } catch (err) {
      wx.showToast({
        title: '加载个人信息失败，请重启小程序',
        icon: 'none'
      })
      wx.navigateBack()
    }

    console.log(user)
    if (user.data.length === 0) {
      wx.showToast({
        title: '授权后才可以使用搜索功能哦~',
        icon: 'none',
        duration: 3000,
        mask: true,
        success: function () {
          setTimeout(function () {
            wx.switchTab({
              url: '/pages/mine/mine',
            })
          }, 2000);
        }
      })
    }
  },

  /**
   * 显示筛选框
   */
  showFilter() {
    this.setData({
      filter: true
    })
  },

  /**
   * 隐藏筛选框
   */
  hiddleFilter() {
    this.setData({
      filter: false
    })
  },

  /**
   * 选择类型
   */
  chooseType(e) {
    let index = e.currentTarget.dataset.index
    let value = e.currentTarget.dataset.value
    let postion = condition.type.indexOf(value)
    if (postion === -1) {
      condition.type.push(value)
      this.setData({
        ["type[" + index + "].isSelect"]: true
      })
    } else {
      condition.type.splice(postion, 1)
      this.setData({
        ["type[" + index + "].isSelect"]: false
      })
    }
  },

  /**
   * 选择类别
   */
  chooseTag(e) {
    let index = e.currentTarget.dataset.index
    let value = e.currentTarget.dataset.value
    let postion = condition.tags.indexOf(value)
    if (postion === -1) {
      condition.tags.push(value)
      this.setData({
        ["tags[" + index + "].isSelect"]: true
      })
    } else {
      condition.tags.splice(postion, 1)
      this.setData({
        ["tags[" + index + "].isSelect"]: false
      })
    }
  },

  /**
   * 选择状态
   */
  chooseStatus(e) {
    let index = e.currentTarget.dataset.index
    let value = e.currentTarget.dataset.value
    let postion = condition.status.indexOf(value)
    if (postion === -1) {
      condition.status.push(value)
      this.setData({
        ["status[" + index + "].isSelect"]: true
      })
    } else {
      condition.status.splice(postion, 1)
      this.setData({
        ["status[" + index + "].isSelect"]: false
      })
    }
  },

  /**
   * 选择时间
   */
  chooseTime(e) {
    let index = e.currentTarget.dataset.index
    let selectIndex = condition.time.index
    if (selectIndex === null) {
      this.setData({
        ["time[" + index + "].isSelect"]: true
      })
    } else {
      if (index == selectIndex) {
        this.setData({
          ["time[" + selectIndex + "].isSelect"]: false
        })
        index = null
      } else {
        this.setData({
          ["time[" + selectIndex + "].isSelect"]: false,
          ["time[" + index + "].isSelect"]: true
        })
      }
    }
    condition.time.index = index

  },

  /**
   * 重置
   */
  reset() {
    let {
      type,
      status,
      time,
      tags
    } = this.data
    for (let item of type) {
      if (item.isSelect) item.isSelect = false
    }
    for (let item of tags) {
      if (item.isSelect) item.isSelect = false
    }
    for (let item of status) {
      if (item.isSelect) item.isSelect = false
    }
    for (let item of time) {
      if (item.isSelect) item.isSelect = false
    }
    condition = {
      type: [],
      tags: [],
      status: [],
      time: {
        index: null,
        start: null,
        end: null
      }
    }
    this.setData({
      type,
      status,
      time,
      tags
    })

  },

  /**
   * 确认
   */
  confirm() {
    let index = condition.time.index
    if (index != null) {
      condition.time.start = this.data.time[index].start
      condition.time.end = this.data.time[index].end
    }
    this.setData({
      result: []
    })
    this._loadData()
    this.hiddleFilter()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    condition = {
      type: [],
      tags: [],
      status: [],
      time: {
        index: null,
        start: null,
        end: null
      }
    }
    this.setData({
      time: [{
        name: '今天',
        start: getDate(-1),
        end: getDate(0)
      }, {
        name: '昨天',
        start: getDate(-2),
        end: getDate(-1)
      }, {
        name: '前天',
        start: getDate(-3),
        end: getDate(-2)
      }, {
        name: '最近7天',
        start: getDate(-6),
        end: getDate(0)
      }],
    })
    this._loadTags()
    this._loadData()
    this._loadPersonalInfo()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      result: []
    })
    this._loadData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.noData) {
      this._loadData()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})